//
//  TWSearchViewController.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/4/19.
//  Copyright © 2017年 个人. All rights reserved.
//

import UIKit
import SVProgressHUD

class TWSearchViewController: UIViewController {
    
    fileprivate lazy var seachBar : UISearchBar = UISearchBar()
    fileprivate lazy var collectionView : UICollectionView = UICollectionView()
    fileprivate lazy var hotWordsArray : [String] = [String]()
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        SVProgressHUD.show()
        loadSearchHotWord()
        setupBeffect()
        setupSearchBar()
        setupCollectionView()
    }
}

// MARK:- UI界面
extension TWSearchViewController {
    fileprivate func setupBeffect(){
        let beffect : UIBlurEffect = UIBlurEffect(style: .extraLight)
        let effectView : UIVisualEffectView = UIVisualEffectView(effect: beffect)
        effectView.frame = view.bounds
        view.addSubview(effectView)
    }
    fileprivate func setupSearchBar(){
        
        seachBar = UISearchBar(frame: CGRect(x: 0, y: 20, width: TWScreenWidth - 40, height: 40))
        seachBar.searchBarStyle = .minimal
        seachBar.placeholder = "帮你找到感兴趣的视频"
        seachBar.returnKeyType = .search
        seachBar.delegate = self
        view.addSubview(seachBar)
        
        let cancelButton : UIButton = UIButton(type: .custom)
        cancelButton.frame = CGRect(x: TWScreenWidth - 40, y: 20, width: 40, height: 40)
        cancelButton.setTitle("取消", for: .normal)
        cancelButton.setTitleColor(UIColor.black, for: .normal)
        cancelButton.titleLabel?.textAlignment = .center
        cancelButton.titleLabel?.font = UIFont(name: "FZLTXIHJW--GB1-0", size: 15)
        cancelButton.addTarget(self, action: #selector(cancelButtonDidClick), for: .touchUpInside)
        view.addSubview(cancelButton)
        
        let warningLabel = UILabel(frame: CGRect(x: 0, y: 60, width: TWScreenWidth, height: 20))
        warningLabel.text = "输入标题或描述中的关键词找到更多视频"
        warningLabel.textColor = UIColor.darkGray
        warningLabel.textAlignment = .center
        warningLabel.font = UIFont(name: "FZLTXIHJW--GB1-0", size: 12)
        view.addSubview(warningLabel)
    }
    fileprivate func setupCollectionView(){
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumInteritemSpacing = 5
        flowLayout.minimumLineSpacing = 5
        flowLayout.scrollDirection = .vertical
        
        collectionView = UICollectionView(frame: CGRect(x: 30, y: 100, width: TWScreenWidth - 60, height: TWScreenHeight - 100), collectionViewLayout: flowLayout)
        collectionView.backgroundColor = UIColor.clear
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UINib(nibName: "TWHotWordCell", bundle: nil), forCellWithReuseIdentifier: "hotCell")
        view.addSubview(collectionView)
    }
}

// MARK:- 监听点击
extension TWSearchViewController {
    @objc fileprivate func cancelButtonDidClick(){
        dismiss(animated: true, completion: nil)
    }
}


// MARK:- 自定义方法
extension TWSearchViewController {
    fileprivate func changeStringKern(string : String) -> NSMutableAttributedString{
        // 调整字间距
        let attributedString : NSMutableAttributedString = NSMutableAttributedString(string: string, attributes: [NSKernAttributeName : 3])
        let paragraphStyle : NSMutableParagraphStyle = NSMutableParagraphStyle()
        attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range:
            NSRange(location: 0, length: (string.characters.count)))
        return attributedString
    }
}


// MARK:- 加载数据
extension TWSearchViewController {
    fileprivate func loadSearchHotWord(){
        TWNetworkTool.shareInstance.loadHotWordsData(urlString: HotWordsUrlString) { (result, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "加载热词失败！")
            }
            guard let result = result else {
                return
            }
            self.hotWordsArray = result
            self.collectionView.reloadData()
            SVProgressHUD.dismiss()
        }
    }
}

// MARK:- 代理
extension TWSearchViewController : UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        seachBar.text = searchText
        print(seachBar.text!)
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        seachBar.resignFirstResponder()
    }
}

extension TWSearchViewController : UICollectionViewDataSource , UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return hotWordsArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hotCell", for: indexPath) as! TWHotWordCell
        let hotWord : String = hotWordsArray[indexPath.item]
        cell.hotWordLabel.attributedText = changeStringKern(string: hotWord)
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let hotWord : String = hotWordsArray[indexPath.item]
        // 计算宽度
        let attributedString = changeStringKern(string: hotWord)
        let font : UIFont = UIFont(name: "FZLTXIHJW--GB1-0", size: 12)!
        let boundingRectW = (attributedString.string as NSString).boundingRect(with: CGSize(width: TWScreenWidth, height: 20), font: font, lineSpacing: LineSpaceing).width
        return CGSize(width: boundingRectW + 20, height: 20)
    }
}


